package cn.ztc.plugin.organism.entity;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.AccessLevel;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * 虫洞<br/>资源访问途径
 *
 * @author ZhangTianCi
 */
@Data
@Slf4j
@TableName("wormhole")
public class Wormhole {
    /**
     * 主键
     */
    @TableId(type = IdType.AUTO)
    private Long id;
    /**
     * 生物主键<br/>唯一的，每个生物拥有一个虫洞
     */
    @TableField("organism_id")
    private Long organismId;
    /**
     * 虫洞内容<br/>[resource_id,resource_id,resource_id,...]
     */
    private String content;
    /**
     * 虫洞内容</br/>拓展
     */
    @TableField(exist = false)
    @Getter(value = AccessLevel.NONE)
    @Setter(value = AccessLevel.NONE)
    private Set<Long> contentExpand;

    public Set<Long> getContentExpand() {
        if (contentExpand == null) {
            try {
                contentExpand = (new ObjectMapper()).readValue(this.getContent(), new TypeReference<Set<Long>>() {{
                }});
            } catch (JsonProcessingException e) {
                log.error("Wormhole.content读取时,序列化失败.", e);
            }
        }
        return Objects.isNull(contentExpand) ? new HashSet<>() : contentExpand;
    }

    public void setContentExpand(Set<Long> contentExpand) {
        try {
            this.setContent((new ObjectMapper()).writeValueAsString(contentExpand));
        } catch (JsonProcessingException e) {
            log.error("Wormhole.content配置时,序列化失败.", e);
        }
    }
}
